<?php

namespace app\api\controller\xiluhouse;

use app\common\controller\Api;
use app\common\model\xiluhouse\Rental as RentalModel;
use app\common\model\xiluhouse\HouseSearchRoomnum;
use app\common\model\xiluhouse\RentalCollection;
use app\common\model\xiluhouse\Village;
use app\common\model\xiluhouse\VillageBroker;
use think\Db;
use think\Exception;

/**
 * @title   租房类
 * @desc    获取租房房源、房源相关信息的接口
 */
class Rental extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['house_list', 'house_detail'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new RentalModel();
    }

    /**
     * @title   地图找房的区县
     * @desc    地图找房的区/县下面小区数量
     * @param string $city   上海市   城市
     * @param string    $keyword          无                    搜索关键词
     */
    public function region_data()
    {
        $city = $this->request->param('city/s', '上海市');
        $map['status'] = 'normal';
        $keyword = $this->request->param('keyword/s', '');
        if ($keyword) {
            $map['name|region'] = ['like', '%' . $keyword . '%'];
        }
        $map['check_status'] = 1;
        $data = Village::field('region,count(*) as count,lat,lng')
            ->where('city', 'like', $city . '%')
            ->where($map)
            ->group('region')
            ->select();
        foreach ($data as $key => $value) {
            $value->visible(['region', 'count', 'lat', 'lng']);
        }
        $this->success('', $data);
    }

    /**
     * @title   地图找房的区县
     * @desc    地图找房的区/县下面小区数量
     * @param string $city   上海市   城市
     * @param string    $keyword          无                    搜索关键词
     */
    public function region_village_data()
    {
        $city = $this->request->param('city/s', '上海市');
        $region = $this->request->param('region/s', '徐汇区');
        $map['status'] = 'normal';
        $keyword = $this->request->param('keyword/s', '');
        if ($keyword) {
            $map['name|region'] = ['like', '%' . $keyword . '%'];
        }
        $data = Village::withCount(['rental'])
            ->field('name,lat,lng')
            ->where('city', 'like', $city . '%')
            ->where('region', 'like', $region . '%')
            ->where($map)
            ->select();
        $new_array = [];
        foreach ($data as $key => $value) {
            if($value['rental_count']>0){
                $value->visible(['name', 'rental_count', 'lat', 'lng']);
                $new_array[] = $value;
            }
        }
        $this->success('', $new_array);
    }

    /**
     * @title  房源列表
     * @desc  获取-房源列表
     * @param string    $city             上海市                城市
     * @param string    $region           无                    区域
     * @param string    $street           无                    街道/镇
     * @param string    $keyword          无                    搜索关键词
     * @param string    $lat              31.235929042252       纬度
     * @param string    $lng              121.48053886018       经度
     * @param tinyint   $nearby           无                    附近几公里
     * @param int       $village_id         无                  小区id
     * @param int       $subway_id         无                   地铁线id
     * @param int       $subway_platform_id 无                  地铁站id
     * @param decimal   $min_price  0                           最小单价（万元）
     * @param decimal   $max_price  0                           最大单价（万元）（-1为无限大）
     * @param string    $search_roomnum_ids 无                   查询户型(多个id用英文逗号隔开)
     * @param int       $rental_mode_id 无                      查询租赁模式(多个id用英文逗号隔开)
     * @param string    $type_ids           无                   查询类型(多个id用英文逗号隔开)
     * @param string    $tag_ids            无                   查询标签(多个id用英文逗号隔开)
     *
     */
    public function house_list()
    {
        $map['village2.city'] = ['like', $this->request->param('city/s', '上海市') . '%'];
        $region = $this->request->param('region/s', '');
        if ($region) {
            $map['village2.region'] = ['like', $region . '%'];
        }
        $village_id = $this->request->param('village_id/d', 0);
        if ($village_id) {
            $map['village_id'] = $village_id;
        }
        $street = $this->request->param('street/s', '');
        if ($street) {
            $map['village2.street'] = ['like', $street . '%'];
        }
        $keyword = $this->request->param('keyword/s', '');
        if ($keyword) {
            $map['rental.name|village2.region'] = ['like', '%' . $keyword . '%'];
        }
        $map_text = '';
        $nearby = $this->request->param('nearby/d', 0);
        if ($nearby) {
            $lat = floatval($this->request->param('lat/s', '31.235929042252'));
            $lng = floatval($this->request->param('lng/s', '121.48053886018'));
            $map_text = '(ACOS(SIN((' . $lat . '*3.1415)/180)*SIN((lat*3.1415)/180)+COS((' . $lat . '*3.1415)/180)*COS((lat*3.1415)/180)*COS((' . $lng . '*3.1415)/180-(lng*3.1415)/180))*6380) <=' . $nearby;
        }
        $subway_id = $this->request->param('subway_id/d', 0);
        if ($subway_id) {
            $map_text = $map_text ? $map_text . ' and ' : $map_text;
            $map_text .= 'FIND_IN_SET(' . $subway_id . ',village2.subway_ids)';
        }
        $subway_platform_id = $this->request->param('subway_platform_id/d', 0);
        if ($subway_platform_id) {
            $map['village2.subway_platform_id'] = $subway_platform_id;
        }


        $min_price = $this->request->param('min_price/f', 0);
        $max_price = $this->request->param('max_price/f', 0);
        if ($max_price > 0) {
            $map['price'] = ['BETWEEN', ($min_price) . ',' . ($max_price)];
        } else if ($max_price == -1) {
            $map['price'] = ['egt', $min_price];
        }

        #租赁模式
        if($rental_mode_id = $this->request->param('rental_mode_id/d', '')){
            $map['rental_mode_id'] = $rental_mode_id;
        }

        $search_roomnum_ids = $this->request->param('search_roomnum_ids/s', '');
        if ($search_roomnum_ids) {
            $search_roomnum_data = \app\common\model\xiluhouse\HouseSearchRoomnum::where('status', 'normal')->where('id', 'in', $search_roomnum_ids)->select();
            $roomnum_map_arr = [];
            foreach ($search_roomnum_data as $value) {
                if ($value['min_room_num'] == -1) {
                    $roomnum_map_arr[] = '(room_num >= ' . $value['min_room_num'] . ')';
                } else {
                    $roomnum_map_arr[] = '((room_num >= ' . $value['min_room_num'] . ' and room_num <= ' . $value['max_room_num'] . ') or (room_num >= ' . $value['min_room_num'] . ' and room_num <= ' . $value['max_room_num'] . '))';
                }
            }
            if (!empty($roomnum_map_arr)) {
                $map_text = $map_text ? $map_text . ' and ' : $map_text;
                $map_text .= implode(' or ', $roomnum_map_arr);
            }
        }

        $type_ids = $this->request->param('type_ids/s', '');
        if ($type_ids) {
            $map['house_type_id'] = ['in', $type_ids];
        }
        //查询房屋特色 例如 1,2,3  多个 字符串
        $tag_ids = $this->request->param('tag_ids/s', '');
        if ($tag_ids) {
            $arr = explode(',', $tag_ids);
            $tag_ids_map_arr = [];
            foreach ($arr as $key => $value) {
                $tag_ids_map_arr[] = 'FIND_IN_SET(' . intval($value) . ',house_tag_ids)';
            }
            if (!empty($tag_ids_map_arr)) {
                $map_text = $map_text ? $map_text . ' and ' : $map_text;
                $map_text .= implode(' or ', $tag_ids_map_arr);
            }
        }
        $map['rental.status'] = 'normal';
        $map['rental.state'] = 1;
        $order = ['weigh' => 'desc', 'id' => 'desc'];
        //halt($map);
        $list = $this->model->with(['village2'=>function($query){
            $query->withField(['id','name','prov','city','region','addr','subway_ids','subway_platform_id']);
        }])
            ->where($map)
            ->where($map_text)
            ->order($order)
            ->paginate();
        foreach ($list as $datas) {
            $datas->visible(['id','name','village_id','price','image','room_num','ting_num','wei_num','space','face','floor_num','house_type_id','house_tag_ids','village2','house_tag_ids_text_arr']);
            $datas->house_tag_ids_text_arr = $datas->rentalTags();
            //$datas->append(['house_tag_ids_text_arr']);
        }
        $this->success('', $list);
    }

    /**
     * @title   房源详情
     * @desc    房源详情
     * @param int $id   0   房源id
     */
    public function house_detail()
    {
        $id = $this->request->param('id/d', 0);
        if (!$id) {
            $this->error('参数错误');
        }

        $lat = floatval($this->request->param('lat/s', '31.235929042252'));
        $lng = floatval($this->request->param('lng/s', '121.48053886018'));
        $field = '(ACOS(SIN((' . $lat . '*3.1415)/180)*SIN((lat*3.1415)/180)+COS((' . $lat . '*3.1415)/180)*COS((lat*3.1415)/180)*COS((' . $lng . '*3.1415)/180-(lng*3.1415)/180))*6380) distance';

        $info = $this->model->field("*,$field")->with(['housetype', 'village2'])->find($id);
        if (!$info) {
            $this->error('查询不到该房源');
        }
        if ($info['state'] != 1) {
            $this->error('该房源已下架');
        }
        if ($info['status'] != 'normal') {
            $this->error('该房源已下架');
        }
        $info->distance = $info->distance < 1 ? sprintf("%.2f",$info->distance*1000).'m' : sprintf("%.2f",$info->distance).'km';
        //房源标签
        $info->house_tag_ids_text_arr = $info->rentalTags();
        //房源信息
        $info->building_descript_arr = $info->rentalTags(2);
        //房源
        $info->append(['images_arr', 'mapimg']);
        $info->village2->append(['nearby_bus_json_arr', 'nearby_subway_json_arr', 'nearby_school_json_arr', 'nearby_shop_json_arr', 'nearby_hospital_json_arr',]);
        // 处理获取静态地图图片
        $info['mapimg']=getGeoImg($info['village2']['lat'],$info['village2']['lng']);
        $data['house_info'] = $info;
        #当前小区经纪人
        if($info->is_public == 1){
            $broker_user_ids = VillageBroker::where('village_id',$info->village_id)->column('broker_user_id');
            $brokers = (new \app\common\model\xiluhouse\User)->field(['password','salt','verification','token','joinip','level','loginfailure','loginip','jointime','group_id','email','successions'],true)->with(['extension'])->whereIn("id",$broker_user_ids)->select();
        }else{
            $brokers = (new \app\common\model\xiluhouse\User)->field(['password','salt','verification','token','joinip','level','loginfailure','loginip','jointime','group_id','email','successions'],true)->with(['extension'])->where('id',$info['user_id'])->select();
        }
        $data['house_info']['brokers'] = $brokers;
        // 获取同小区房源
        $data['village_data'] = RentalModel::with(['village2'=>function($query){
            $query->withField(['id','name','prov','city','region','addr','subway_ids','subway_platform_id']);
        }])
            ->where('rental.id', 'neq', $id)
            ->where('village_id', 'eq', $info['village_id'])
            ->where('rental.status', 'normal')
            ->where('rental.state', 1)
            ->where('prov', $info['village2']['prov'])
            ->where('city', $info['village2']['city'])
            ->orderRaw('rand()')
            ->limit(5)
            ->select();
        foreach ($data['village_data'] as $recommend_value) {
            $recommend_value->visible(['id','name','village_id','price','image','room_num','ting_num','wei_num','space','face','floor_num','house_type_id','house_tag_ids','village2','house_tag_ids_text_arr']);
            $recommend_value->house_tag_ids_text_arr = $recommend_value->rentaltags();
        }
        // 获取推荐房源
        $data['recommend_data'] = RentalModel::with(['village2'=>function($query){
            $query->withField(['id','name','prov','city','region','addr','subway_ids','subway_platform_id']);
        }])
            ->where('rental.id', 'neq', $id)
            ->where('rental.status', 'normal')
            ->where('rental.state', 1)
            ->where('prov', $info['village2']['prov'])
            ->where('city', $info['village2']['city'])
            ->orderRaw('rand()')
            ->limit(5)
            ->select();
        foreach ($data['recommend_data'] as $recommend_value) {
            $recommend_value->visible(['id','name','village_id','price','image','room_num','ting_num','wei_num','space','face','floor_num','house_type_id','house_tag_ids','village2','house_tag_ids_text_arr']);
            $recommend_value->house_tag_ids_text_arr = $recommend_value->rentaltags();
        }
        // 给房源添加浏览量
        $info->setInc('view_num');
        $data['house_info']['platform_contact_tel'] = \app\common\model\xiluhouse\Config::getdatas('platform_contact_tel');

        //是否收藏
        $data['house_info']['is_collection'] = $this->auth->isLogin()
            ? RentalCollection::where('rental_id',$id)->where('user_id',$this->auth->id)->count('id') : 0;

        $rentalQrcodeModel = new \app\common\model\xiluhouse\RentalQrcode;
        $exist = $rentalQrcodeModel->where('rental_id', $id)->where('user_id', $this->auth->id)->find();
        if ($exist) {
            $data['share_qrcode_text'] = cdnurl($exist['url'],true);
        } else {
            $wxmini = new \app\common\library\xiluhouse\Wxmini;
            $res = $wxmini->getWXacode('user_' . $this->auth->id . ',rental_' . $id, 'pages/rental/renting/renting');
            if($res){
                $root = '.';
                $filename = md5(mt_rand()).'.png';
                $path = "/uploads/".date('Ymd').'/';
                if (!file_exists($root . $path)) {
                    @mkdir($root . $path, 0777, true);
                }
                $qrcode = $path.$filename;
                if(!get_addon_config('alioss')){
                    file_put_contents($root.$qrcode,$res);
                }else{
                    Common::uploadAlioss($qrcode, $res);
                }
                if ($qrcode) {
                    $rentalQrcodeModel->insert(['rental_id' => $id, 'user_id' => $this->auth->id, 'url' => $qrcode]);
                }
                $data['share_qrcode_text'] = cdnurl($qrcode ? $qrcode : \app\common\model\xiluhouse\Config::getdatas('wxmini_logo'),true);
            }
        }

        $this->success('', $data);
    }

    /**
     * 废弃
     * @title   留电咨询
     * @desc    留电咨询
     * @param int $rental_id                     0    租房id
     * @param int $broker_user_id               0    关联经纪人id
     * @param string $mobile                    无   手机号
     * @param string $prov                      无   省
     * @param string $city                      无   省
     * @param string $region                    无   省
     */
    public function create_appoint_log()
    {
        $param['type'] = 2;
        $param['subscribe_type'] = 0;
        $param['rental_id'] = $this->request->param('rental_id/d', 0);
        $param['user_id'] = $this->auth->id;
        $param['broker_user_id'] = $this->request->param('broker_user_id/d', 0);
        $param['mobile'] = $this->request->param('mobile/s', '');
        $param['prov'] = $this->request->param('prov/s', '');
        $param['city'] = $this->request->param('city/s', '');
        $param['region'] = $this->request->param('region/s', '');
        if ($param['broker_user_id'] == $param['user_id']) {
            $this->error('无法预约自己哦');
        }
        $model = new \app\common\model\xiluhouse\AppointLog;
        $res = $model->save($param);
        if (!$res) {
            $this->error('提交失败');
        }
        $this->success('提交成功');
    }

    /**
     * @ApiTitile (收藏&取消收藏)
     * @ApiSummary (收藏&取消收藏)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xiluehouse.rental/toggle_collection)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     * @ApiParams (name=rental_id, type=int, require=true, description="id")
     */
    public function toggle_collection() {
        $rental_id = $this->request->post('rental_id');
        $user_id = $this->auth->id;
        Db::startTrans();
        try {
            $model = RentalCollection::where('user_id', $user_id)
                ->where('rental_id', $rental_id)
                ->find();
            if ($model) {
                $model->delete();
                $result = false;
            } else {
                $model = new RentalCollection([
                    'user_id' => $user_id,
                    'rental_id' => $rental_id
                ]);
                if ($model->save() === false) {
                    Db::rollback();
                    throw new Exception($model->getError());
                }
                $result = true;
            }
            $collectionCount = RentalCollection::where('rental_id', $rental_id)->count();
            RentalModel::where('id', $rental_id)->update(['collection_num' => $collectionCount]);
        }catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('操作成功',['is_collection'=>$result?1:0]);
    }

}
